package com.kfgj.hkp.common.dataaccess.redis;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kfgj.hkp.common.logging.Logger;
import com.kfgj.hkp.common.logging.LoggerFactory;
import com.kfgj.hkp.common.utils.GenericsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.hash.DecoratingStringHashMapper;
import org.springframework.data.redis.hash.HashMapper;
import org.springframework.data.redis.hash.Jackson2HashMapper;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.TimeUnit;


public abstract class AbstractRedisDao<T> implements IRedisDao<T> {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    protected Class<T> entityClass = GenericsUtils.getSuperClassGenricType(this.getClass());
    protected ValueOperations<String, String> valueOps;
    protected SetOperations<String, String> setOps;
    protected ZSetOperations<String, String> zSetOps;
    protected ListOperations<String, String> listOps;
    protected HashMapper<T, String, String> mapper;

    protected StringRedisTemplate template;

    protected ObjectMapper objectMapper;

    public AbstractRedisDao() {
//        this.mapper = new DecoratingStringHashMapper(new JacksonHashMapper(this.entityClass));
        this.mapper = new DecoratingStringHashMapper(new Jackson2HashMapper(true));
        this.objectMapper = new ObjectMapper();
    }

    @PostConstruct
    private void afterInitialization() {
        this.valueOps = this.template.opsForValue();
        this.setOps = this.template.opsForSet();
        this.zSetOps = this.template.opsForZSet();
        this.listOps = this.template.opsForList();
    }

    public StringRedisTemplate getTemplate() {
        return this.template;
    }

    @Autowired(required = false)
    @Qualifier("stringRedisTemplate2")
    public void setTemplate(StringRedisTemplate template) {
        this.template = template;
    }

    @Override
    public void saveEntity(String key, T t) throws JsonProcessingException {
        String result = objectMapper.writeValueAsString(t);
        valueOps.set(key, result);
    }

    @Override
    public T parseEntity(String key) throws IOException {
        String result = valueOps.get(key);
        return objectMapper.readValue(result, entityClass);
    }

    /**
     * 设置多少秒后redis存储失效
     *
     * @param key
     * @param timeoutSecond
     */
    @Override
    public void setTimeout(String key, long timeoutSecond) {
        template.expire(key, timeoutSecond, TimeUnit.SECONDS);
    }

    @Override
    public void setTimeout(String key, Date date) {
        template.expireAt(key,date);
    }


}
